<template>
  <drag-modal
    title="编辑"
    :width="500"
    :visible="visible"
    :destroyOnClose="true"
    :confirmLoading="submitLoading"
    :maskClosable="false"
    @ok="ok"
    @cancel="cancel"
  >
    <a-spin :spinning="loading">
      <a-form-model :model="form" ref="form" :rules="validatorRules" :label-col="{span: 5}" :wrapperCol="{span: 16, offset: 1}">
        <div class="fold">
          <a-form-model-item
            label="所属机构"
            prop="organizationId"
          >
            <a-tree-select
              show-search :filterTreeNode="filterTreeNode" 
              v-model="form.organizationId"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
              :tree-data="organizationTreeData"
              :tree-default-expand-all="true"
              :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
              @change="onOrganizationIdChange"
            >
              <template slot="title" slot-scope="item">
                <span v-if="item.type == 0"><a-icon type="bank" /> {{item.customTitle}} </span>
                <span v-else-if="item.type == 1"><a-icon type="shop" /> {{item.customTitle}} </span>
                <span v-else-if="item.type == 2"><a-icon type="apartment" /> {{item.customTitle}} </span>
                <span v-else><a-icon type="question-circle" /> {{item.customTitle}} </span>
              </template>
            </a-tree-select>
          </a-form-model-item>
          <a-form-model-item
            label="名称"
            prop="name"
          >
            <a-input allowClear v-model="form.name" />
          </a-form-model-item>
          <a-form-model-item
            label="编号"
            prop="code"
          >
            <a-input disabled allowClear v-model="form.code" />
          </a-form-model-item>
          <a-form-model-item
            label="硬件编号"
            prop="hardwareCode"
          >
            <a-input disabled allowClear v-model="form.hardwareCode" />
          </a-form-model-item>
          <a-form-model-item
            label="所属城市"
            prop="cityId"
          >
            <a-select show-search :filter-option="filterOption" v-model="form.cityId" :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}" @search="onCitySearch" @popupScroll="onCityPopupScroll">
              <a-select-option v-for="item in cityDataList" :key="item.key" :value="item.value">{{item.title}}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            label="所属分组"
            prop="groupId"
          >
            <a-row>
              <a-col :span="24">
                <a-tree-select
                  allowClear
                  show-search :filterTreeNode="groupFilterTreeNode" 
                  v-model="form.groupId"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
                  :tree-data="groupTreeData"
                  :tree-default-expand-all="true"
                  :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
                >
                </a-tree-select>
              </a-col>
            </a-row>
          </a-form-model-item>
        </div>
      </a-form-model>
    </a-spin>
  </drag-modal>
</template>

<script>
  import {terminalService} from '@/services'
  export default {
    name: 'EditModal',
    props: {
      visible: {
        type: Boolean,
        required: true
      }
    },
    data() {
      return {
        loading: false,
        submitLoading: false,
        groupTreeLoading: false,
        organizationTreeData: [],
        groupTreeData: [],
        groupExpandedKeys: [],
        cityTotalDataList: [],
        cityDataList: [],
        cityPageSize: 50,
        cityPage: 1,
        citySearchValue: '',
        form: {
          name: undefined,
          code: undefined,
          type: undefined,
          hardwareCode: undefined,
          organizationId: undefined,
          groupId: undefined,
          cityId: undefined,
        },
        validatorRules: {
          organizationId: [
            { required: true, message: '请选择组织机构', trigger: 'change' }
          ],
          name: [
            { required: true, message: '请输入名称', trigger: 'blur' }
          ],
          code: [
            { required: true, message: '请输入编号', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      cancel() {
        this.$emit('cancel')
      },
      ok() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.submitLoading = true
            terminalService.edit(JSON.stringify(this.form)).then(res => {
              const result = res.data
              if (result.code === 200) {
                this.$emit('ok')
                this.$message.success(result.msg)
              }
            }).finally(this.submitLoading = false)
          }
        })
      },
      pushRouterGroup() {
        this.$emit('cancel')
        this.$router.push('/device/group')
      },
      pushRouterBusLine() {
        this.$emit('cancel')
        this.$router.push('/device/busLine')
      },
      onOrganizationIdChange(val) {
        this.form.groupId = undefined
        this.form.organizationId = val
        this.queryGroupSelectAction(val)
      },
      onClickTreeNode(selectedKeys) {
        this.form.groupId = selectedKeys[0]
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.indexOf(input) >= 0
        )
      },
      filterTreeNode(input, treeNode) {
        return treeNode.data.props.customTitle.includes(input)
      },
      groupFilterTreeNode(input, treeNode) {
        return treeNode.data.props.title.includes(input)
      },
      onCitySearch(input) {
        this.citySearchValue = input
        if (!input) {
          this.queryCitySelectAction()
        } else {
          this.cityDataList = []
          this.cityPage = 1
          let newCityData = []
          this.cityTotalDataList.forEach((item, index) => {
            if (item.title.indexOf(input) >= 0) {
              newCityData.push(item)
            }
          })
          this.cityDataList = [...this.cityDataList, ...newCityData.slice(0, this.cityPageSize)]
        }
      },
      onCityPopupScroll(e) {
        const { scrollHeight, scrollTop, clientHeight } = e.target
        // 下拉框不下拉的时候
        if (scrollHeight === 0 && clientHeight === 0) {
          this.cityPage = 1
        } else {
          // 当下拉框滚动条到达底部的时候
          if (scrollHeight - scrollTop === clientHeight) {
            this.cityPage += 1
            // 获取当前页码
            let cityPage = this.cityPage
            let newCityData = []
            // 得到需要开始拼接的数据下标
            let cursorStart = (cityPage - 1) * this.cityPageSize
            // 得到需要结束拼接的数据下标
            let cursorEnd = cityPage * this.cityPageSize
            // 判断是否有搜索
            if (this.citySearchValue) {
              let temp = []
              this.cityTotalDataList.forEach((item, index) => {
                if (item.title.indexOf(this.citySearchValue) >= 0) {
                  temp.push(item)
                }
              })
              temp.forEach((item, index) => {
                if (index >= cursorStart && index < cursorEnd) {
                  newCityData.push(item)
                }
              })
            } else {
              this.cityTotalDataList.forEach((item, index) => {
                if (index >= cursorStart && index < cursorEnd) {
                  newCityData.push(item)
                }
              })
            }
             // 将新增的数据赋值到要显示的数组中
            this.cityDataList = [...this.cityDataList, ...newCityData]
          }
        }
      },
      queryAction(val) {
        this.loading = true
        const params = {
          id: val
        }
        terminalService.query(JSON.stringify(params)).then(res => {
          const result = res.data
          if (result.code === 200) {
            this.form = result.data
          }
        }).finally(this.loading = false)
      },
      queryGroupSelectAction(val) {
        this.loading = true
        const params = {
          organizationId: val
        }
        terminalService.queryGroupTreeSelect(JSON.stringify(params)).then(res => {
          const result = res.data
          if (result.code === 200) {
            this.groupTreeData = result.data
            this.groupExpandedKeys = []
            this.expandAllTreeNode(this.groupTreeData, this.groupExpandedKeys)
          }
        }).finally(this.loading = false)
      },
      queryCitySelectAction() {
        terminalService.queryCitySelect().then(res => {
          const result = res.data
          if (result.code === 200) {
            let tempCityDataList = result.data
            if (tempCityDataList && tempCityDataList.length > 0) {
              this.cityTotalDataList = tempCityDataList
              this.cityDataList = tempCityDataList.slice(0, this.cityPageSize)
              // 判断上级是否在cityDataList中
              let index = this.cityDataList.findIndex(item => item.key == this.form.cityId)
              // 如果不存在
              if (index == -1) {
                let currentItem = {
                  key: this.form.cityId,
                  title: this.form.cityName,
                  value: this.form.cityId
                }
                // 插入到cityDataList的开头
                this.cityDataList.unshift(currentItem)
                // 重新slice分页大小
                this.cityDataList = this.cityDataList.slice(0, this.cityPageSize)
                // 插入到总数据的开头
                this.cityTotalDataList.unshift(currentItem)
                // 删除总数据中的该条目
                this.cityTotalDataList = this.cityTotalDataList.filter((item, index) => index == 0 || item.key != this.form.cityId)
              }
            }
          }
        }).finally()
      },
      queryOrganizationTreeAction(val) {
        this.loading = true
        this.form.organizationId = val
        terminalService.queryOrganizationTree().then(res => {
          const result = res.data
          if (result.code === 200) {
            this.organizationTreeData = result.data
          }
        }).finally(this.loading = false)
      },
      expandAllTreeNode(originData, targetData) {
        originData.forEach(item => {
          targetData.push(item.key)
          if (item.children && item.children.length > 0) {
            this.expandAllTreeNode(item.children, targetData)
          }
        })
      }
    }
  }
</script>